<?php

/**
 * Created by 无所谓已
 * User: Administrator
 * Date: 2025-08-18
 * Time: 13:36
 */

namespace plugin\csauto\app\service\downloader;

use plugin\csauto\app\model\DownloaderModel;
use plugin\csauto\app\model\TorrentListModel;
use plugin\csauto\app\model\TorrentReleaseModel;
use plugin\csauto\app\model\TorrentTaskModel;
use plugin\csauto\app\service\ApiWorkService;
use plugin\csauto\app\service\QBittorrentService;
use plugin\csauto\app\service\release\ReleaseService;
use plugin\csauto\app\service\SiteRulesWorkService;
use plugin\csauto\app\service\SiteWorkService;
use plugin\csauto\app\service\SystemService;
use plugin\csauto\app\service\TorrentListService;
use support\Db;
use support\Log;
use function Symfony\Component\Clock\now;

class DownloaderWorkService
{
    public static $sourceSiteCategory = '[源站种]';
    public static $releaseSiteCategory = '[发布种]';
    public static $releaseCompleteNum = 5;
    public static $defaultFilePath = '/Downloads';

    /**
     * Created by 无所谓已
     * Date: 2025-08-18
     * Time: 18:14
     * addDownloadTask
     * 向下载器添加新任务
     *
     * @param       $downloaderModel
     * @param array $options
     * @return bool
     */
    public static function addDownloadTask($downloaderModel, $options = array())
    {
        $qb = QBittorrentService::createService($downloaderModel->id);
        if (!$qb) return false;/*无法获取下载器的信息*/
        /*获取所有需要下载的任务（考虑下载器任务种子体积范围）*/
        $torrentTaskData = null;
        $minSizeGb = intval($downloaderModel->task_torrent_min_size ?? 0);
        $maxSizeGb = intval($downloaderModel->task_torrent_max_size ?? 0);

        if ($minSizeGb <= 0 && $maxSizeGb <= 0) {
            $torrentTaskData = TorrentTaskModel::where('downloader_id', $downloaderModel->id)
                ->where('down_status', 0)
                ->orderBy('updated_at')
                ->first();
        } else {
            $candidates = TorrentTaskModel::where('downloader_id', $downloaderModel->id)
                ->where('down_status', 0)
                ->orderBy('updated_at')
                ->limit(100)
                ->get();
            foreach ($candidates as $candidate) {
                $listData = TorrentListService::getTorrentListData($candidate->site_id, $candidate->torrent_id);
                if (!$listData) continue;
                $sizeGb = convertToGB($listData->torrents_size);
                if ($minSizeGb > 0 && $sizeGb < $minSizeGb) continue;
                if ($maxSizeGb > 0 && $sizeGb > $maxSizeGb) continue;
                $torrentTaskData = $candidate;
                break;
            }
            if (!$torrentTaskData) {
                addlog('addDownloadTask', "下载器{$downloaderModel->id} 无满足体积范围的待添加任务(min={$minSizeGb}GB,max={$maxSizeGb}GB)");
                return false;
            }
        }
        if ($torrentTaskData) {
            $tag = [];
            $tag[] = "[-CSAUTO]";
            $tag[] = "[-" . SiteWorkService::siteName($torrentTaskData->site_id) . "]";
            $tag[] = "[{$torrentTaskData->torrent_hash}]";
            //            if (SystemService::getConfig(SystemService::TASK_DL_LIMIT) > 0) {
            //                $options['dlLimit'] = SystemService::getConfig(SystemService::TASK_DL_LIMIT) * 1024;
            //            }
            
            // 设置下载限速
            if ($downloaderModel->down_speed > 0) $options['dlLimit'] = intval(intval($downloaderModel->down_speed) * 1024 * 1024);
            
            // 设置上传限速（源站种子）
            $up_speed = 0;
            if ($downloaderModel->up_speed > 0) {
                $up_speed = $downloaderModel->up_speed;
            }
            // 检查站点上传限速规则
            $siteUpSpeed = (int)SiteWorkService::siteUpSpeed($torrentTaskData->site_id);
            if ($siteUpSpeed > 0) {
                addlog('addDownloadTask', "源站种子存在站点限速 {$siteUpSpeed}MB/S，站点ID：{$torrentTaskData->site_id}");
                $up_speed = $siteUpSpeed;
            }
            if ($up_speed > 0) $options['upLimit'] = intval(intval($up_speed) * 1024 * 1024);
            
            if (!$qb->addTorrentByFile($torrentTaskData->torrent_path, self::$defaultFilePath, self::$sourceSiteCategory, $tag, $options)) {
                /*开抛异常*/
                addlog('下载器添加新任务', '任务添加失败', 'error');
                return false;
            }
            $torrentTaskData->down_status = 1;

            return $torrentTaskData->save();
        }
        return false;
    }

    /**
     * Created by 无所谓已
     * Date: 2025-08-18
     * Time: 18:14
     * checkDownloadTask
     * 检查下载任务是否完成
     *
     * @param $downloaderModel
     * @return false
     */
    public static function checkDownloadTask($downloaderModel)
    {
        /*先拉取一下进行下载中的任务信息*/
        $torrentTaskHash = array();
        $torrentTaskList = TorrentTaskModel::where('downloader_id', $downloaderModel->id)->where('status', 1)->where('down_status', 1)->get();
        foreach ($torrentTaskList as $item) {
            $torrentTaskHash[$item->torrent_hash] = $item;
        }
        if (count($torrentTaskHash) < 1) return false;/*没有待检查的数量直接结束*/
        $qb = QBittorrentService::createService($downloaderModel->id);
        if (!$qb) return false;/*无法获取下载器的信息*/
        $torrentsList = $qb->getTorrents();
        //        return $torrentsList;
        foreach ($torrentsList as $item) {
            if ($item['category'] == self::$sourceSiteCategory && ($item['state'] == "stalledUP" || $item['completion_on'] > 0)) {
                if (isset($torrentTaskHash[$item['hash']])) {
                    /*接受到了新的完成通知*/
                    addlog('checkDownloadTask', "下载器{$downloaderModel->id}接收到下载完成通知，hash：{$item['hash']}");
                    $torrentTaskHash[$item['hash']]->down_status = 2;
                    $torrentTaskHash[$item['hash']]->down_path = self::$defaultFilePath . "/{$item['name']}";
                    $torrentTaskHash[$item['hash']]->down_time = time();
                    $torrentTaskHash[$item['hash']]->save();
                }
            }
        }
    }


    /**
     * Created by 无所谓已
     * Date: 2025-08-18
     * Time: 18:52
     * getMediaInfoUpdate
     * 为待处理的任务更新 MediaInfo（带重试机制）
     *
     * @param $taskData
     * @return bool
     */
    public static function getMediaInfoUpdate($taskData)
    {
        // 获取最大重试次数配置
        $maxRetryCount = SystemService::getConfig(SystemService::MEDIAINFO_RETRY_MAX_COUNT);
        if (!$maxRetryCount || $maxRetryCount <= 0) {
            $maxRetryCount = 10; // 默认重试10次
        }

        // 检查当前重试次数
        $currentRetryCount = $taskData->mediainfo_retry_count ?? 0;

        // 如果达到最大重试次数，终止任务
        if ($currentRetryCount >= $maxRetryCount) {
            addlog('getMediaInfoUpdate', "任务 " . $taskData->id . " 达到最大重试次数 {$maxRetryCount}，终止任务");
            return self::terminateTask($taskData);
        }

        /*获取他文件列表的第一个文件*/
        try {
            $qb = QBittorrentService::createService($taskData->downloader_id);
            if (!$qb) {
                // 无法获取下载器信息，重试计数+1
                $taskData->mediainfo_retry_count = $currentRetryCount + 1;
                $taskData->save();
                addlog('getMediaInfoUpdate', "任务 " . $taskData->id . " 无法获取下载器信息，重试 " . ($currentRetryCount + 1) . "/{$maxRetryCount}");
                return false;/*无法获取下载器的信息*/
            }

            $torrentFiles = $qb->getTorrentFiles($taskData->torrent_hash);
            if (empty($torrentFiles)) {
                // 无法获取种子文件，重试计数+1
                $taskData->mediainfo_retry_count = $currentRetryCount + 1;
                $taskData->save();
                addlog('getMediaInfoUpdate', "任务 " . $taskData->id . " 无法获取种子文件，重试 " . ($currentRetryCount + 1) . "/{$maxRetryCount}");
                return false;
            }

            $filePath = self::$defaultFilePath . '/' . $torrentFiles[0]['name'];
            /*获取登录API的接口信息*/
            $downloaderData = DownloaderModel::where('id', $taskData->downloader_id)->first();
            if (!$downloaderData) {
                // 无法获取下载器数据，重试计数+1
                $taskData->mediainfo_retry_count = $currentRetryCount + 1;
                $taskData->save();
                addlog('getMediaInfoUpdate', "任务 " . $taskData->id . " 无法获取下载器数据，重试 " . ($currentRetryCount + 1) . "/{$maxRetryCount}");
                return false;
            }

            $mediaInfoDetails = ApiWorkService::MediaInfoDetails("http://{$downloaderData->d_host}:{$downloaderData->w_port}/api/getMediaInfo", $filePath);

            if (!$mediaInfoDetails || !isset($mediaInfoDetails['mediainfo'])) {
                // MediaInfo获取失败，重试计数+1
                $taskData->mediainfo_retry_count = $currentRetryCount + 1;
                $taskData->save();
                addlog('getMediaInfoUpdate', "任务 " . $taskData->id . " MediaInfo获取失败，重试 " . ($currentRetryCount + 1) . "/{$maxRetryCount}");
                return false;
            }

            $taskData->mediaInfo = $mediaInfoDetails['mediainfo'];

            /*顺便检查一下详情是否需要截图操作*/
            $torrentListData = TorrentListService::getTorrentListData($taskData->site_id, $taskData->torrent_id);
            if ($torrentListData) {
                $checkResourceTailImages = checkResourceTailImages($torrentListData->torrents_view);
                if ($checkResourceTailImages < SystemService::getConfig(SystemService::TORRENT_VIEW_IMG_MIN_NUM) && empty($taskData->torrents_view_img)) {
                    /*开始进行请求截图操作*/
                    $imgInfoDetails = ApiWorkService::imgInfoDetails("http://{$downloaderData->d_host}:{$downloaderData->w_port}/api/getImgInfo", $filePath);
                    if ($imgInfoDetails) {
                        $taskData->torrents_view_img = convertDataArrayToImgTags($imgInfoDetails);
                    }
                }
            }

            // 成功获取MediaInfo，重置重试计数并标记完成
            $taskData->mediaInfo_status = 2;
            $taskData->mediainfo_retry_count = 0; // 重置重试计数
            $taskData->save();

            addlog('getMediaInfoUpdate', "任务 " . $taskData->id . " MediaInfo获取成功");
            return true;
        } catch (\Throwable $e) {
            // 发生异常，重试计数+1
            $taskData->mediainfo_retry_count = $currentRetryCount + 1;
            $taskData->save();

            Log::info('getMediaInfoUpdate', array(
                'error' => $e->getMessage(),
                'task_id' => $taskData->id,
                'retry_count' => $currentRetryCount + 1,
                'max_retry' => $maxRetryCount
            ));

            addlog('getMediaInfoUpdate', "任务 " . $taskData->id . " 发生异常，重试 " . ($currentRetryCount + 1) . "/{$maxRetryCount}: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 终止任务并清理资源
     *
     * @param $taskData
     * @return bool
     */
    private static function terminateTask($taskData)
    {
        try {
            // 标记主任务为失败状态
            $taskData->status = 99;
            $taskData->save();

            // 检查下载器是否存在
            $downloaderExists = DownloaderModel::where('id', $taskData->downloader_id)->exists();
            
            if ($downloaderExists) {
                // 下载器存在，清理下载器中的种子文件
                $qb = QBittorrentService::createService($taskData->downloader_id);
                if ($qb) {
                    // 删除源站种子
                    $qb->deleteTorrent($taskData->torrent_hash, true);
                    addlog('terminateTask', "已删除下载器中的源站种子 {$taskData->torrent_hash}");
                }
            } else {
                addlog('terminateTask', "下载器已被删除，跳过QB操作，直接清理任务 {$taskData->id}");
            }

            // 清理相关的发布任务
            $releaseTasks = TorrentReleaseModel::where('task_id', $taskData->id)->get();
            foreach ($releaseTasks as $releaseTask) {
                // 标记发布任务为失败
                $releaseTask->status = 99;
                $releaseTask->task_status = 99;
                $releaseTask->save();

                // 如果发布任务已经上传到下载器，检查下载器是否存在再清理
                if ($releaseTask->torrents_hash) {
                    $releaseDownloaderExists = DownloaderModel::where('id', $releaseTask->downloader_id)->exists();
                    if ($releaseDownloaderExists) {
                        $qb = QBittorrentService::createService($releaseTask->downloader_id);
                        if ($qb) {
                            $qb->deleteTorrent($releaseTask->torrents_hash, true);
                        }
                    }
                }
            }

            addlog('terminateTask', "任务 " . $taskData->id . " 已终止，共清理了 " . count($releaseTasks) . " 个发布任务");
            return true;
        } catch (\Throwable $e) {
            addlog('terminateTask', "终止任务 " . $taskData->id . " 时发生错误: " . $e->getMessage(), 'error');
            return false;
        }
    }


    /**
     * Created by 无所谓已
     * Date: 2025-08-18
     * Time: 21:43
     * getDownloaderLoadBalance
     * 获取下载器负载均衡列表，按负载比例排序（最低负载优先）
     *
     * @return array
     */
    public static function getDownloaderLoadBalance()
    {
        $downloaderList = [];
        $activeDownloaders = DownloaderModel::where('status', 1)->get();

        foreach ($activeDownloaders as $downloader) {
            // 计算当前正在进行的任务数量（下载中和发布中的任务）
            $activeTasks = 0;

            // 下载任务：status=1, down_status=1 (正在下载)
            $downloadingTasks = TorrentTaskModel::where('downloader_id', $downloader->id)
                ->where('status', 1)
                ->where('down_status', 1)
                ->count();

            // 发布任务：status=2, task_status=1 (正在发布)
            $publishingTasks = TorrentReleaseModel::where('downloader_id', $downloader->id)
                ->where('status', 2)
                ->where('task_status', 1)
                ->count();

            $activeTasks = $downloadingTasks + $publishingTasks;

            // 计算负载比例
            $effectiveTaskLimit = $downloader->getEffectiveTaskLimit();
            $taskLimit = $effectiveTaskLimit > 0 ? $effectiveTaskLimit : 10; // 默认限制为10
            $loadRatio = $taskLimit > 0 ? ($activeTasks / $taskLimit) : 0;

            $downloaderList[] = [
                'downloader' => $downloader,
                'active_tasks' => $activeTasks,
                'task_limit' => $taskLimit,
                'load_ratio' => $loadRatio
            ];
        }

        // 按负载比例排序（最低负载优先）
        usort($downloaderList, function ($a, $b) {
            return $a['load_ratio'] <=> $b['load_ratio'];
        });

        return $downloaderList;
    }

    /**
     * Created by 无所谓已
     * Date: 2025-08-18
     * Time: 21:43
     * assignPublishingTasks
     * 智能分配发布任务给负载最低的下载器
     *
     * @param $taskData
     * @return bool
     */
    public static function assignPublishingTasks(TorrentTaskModel $taskData)
    {
        /*拉取所有的站点规则*/
        $siteRules = SiteRulesWorkService::getSiteRulesList();
        $taskListItem = TorrentListModel::where('site_id', $taskData->site_id)->where('torrent_id', $taskData->torrent_id)->first();

        // 获取负载均衡的下载器列表
        $downloaderList = self::getDownloaderLoadBalance();
        if (empty($downloaderList)) {
            addlog('assignPublishingTasks', '无可用的下载器', 'warning');
            return false;
        }

        DB::beginTransaction();
        try {
            $assignedTasks = 0;
            foreach (SiteWorkService::getOutSiteList() as $siteId) {
                if ($taskData->site_id == $siteId) continue;

                // 检查目标站点的passkey是否为空，如果为空则跳过该站点的发布任务生成
                $targetSiteData = SiteWorkService::getSiteData($siteId);
                if (empty($targetSiteData->site_passkey)) {
                    addlog('assignPublishingTasks', "站点 {$targetSiteData->site_name} (ID: {$siteId}) 的passkey为空，跳过生成发布任务");
                    continue;
                }

                if (!SiteRulesWorkService::checkSiteRules($siteRules, $taskData, $taskListItem, $siteId)) continue;
                $model = new TorrentReleaseModel;
                $model->downloader_id = $taskData->downloader_id;
                $model->site_id = $siteId;
                $model->task_id = $taskData->id;
                $model->status = 1;
                $model->save();
                $assignedTasks++;
            }

            if ($assignedTasks > 0) {
                $taskData->release_time = time();
                $taskData->status = 2;
                $taskData->save();
                Db::commit();

                addlog('assignPublishingTasks', "成功分配 {$assignedTasks} 个发布任务");
                return true;
            } else {
                Db::rollBack();
                addlog('assignPublishingTasks', '没有分配任何发布任务', 'warning');
                return false;
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            addlog('assignPublishingTasks', array(
                'msg' => $exception->getMessage(),
                'line' => $exception->getLine(),
                'file' => $exception->getFile(),
                'tr' => $exception->getTrace()
            ), 'error');
            return false;
        }
    }

    public static function releaseTask($torrentRelease)
    {
        addlog('releaseTask', "开始处理任务ID：{$torrentRelease->id}");

        // 获取主任务数据
        $taskData = TorrentTaskModel::where('id', $torrentRelease->task_id)->first();

        // 检查主任务是否存在
        if (!$taskData) {
            addlog('releaseTask', "任务 {$torrentRelease->id} 的主任务不存在，跳过发布");
            $torrentRelease->task_status = 4;
            $torrentRelease->status = 99;
            $torrentRelease->save();
            return 99; // 主任务不存在
        }

        // 检查主任务是否已经结束
        if ($taskData->status == 99) {
            addlog('releaseTask', "任务 {$torrentRelease->id} 的主任务已结束，跳过发布");
            $torrentRelease->task_status = 5;
            $torrentRelease->status = 99;
            $torrentRelease->save();
            return 99; // 主任务已结束
        }

        // 检查下载器是否存在
        $downloaderExists = DownloaderModel::where('id', $taskData->downloader_id)->exists();
        
        if (!$downloaderExists) {
            // 下载器已被删除，直接标记任务失败
            addlog('releaseTask', "任务 {$torrentRelease->id} 的下载器 {$taskData->downloader_id} 已被删除，标记任务失败");
            $torrentRelease->task_status = 6; // 源站种子不存在（下载器已删除）
            $torrentRelease->status = 99;
            $torrentRelease->save();
            return 99;
        }
        
        // 检查源站种子是否还在下载器中
        $qb = QBittorrentService::createService($taskData->downloader_id);
        if ($qb) {
            $torrentsList = $qb->getTorrents();
            $sourceTorrentExists = false;

            foreach ($torrentsList as $torrent) {
                if ($torrent['hash'] === $taskData->torrent_hash) {
                    $sourceTorrentExists = true;
                    break;
                }
            }

            if (!$sourceTorrentExists) {
                addlog('releaseTask', "任务 {$torrentRelease->id} 的源站种子 {$taskData->torrent_hash} 不在下载器中，跳过发布");
                $torrentRelease->task_status = 6;
                $torrentRelease->status = 99;
                $torrentRelease->save();
                return 99; // 源站种子不存在
            }
        } else {
            // 下载器存在但无法连接，应用重试机制
            $currentRetryCount = $torrentRelease->retry_count ?? 0;
            $maxRetryCount = SystemService::getConfig(SystemService::RELEASE_RETRY_MAX_COUNT) ?? 10;
            
            $currentRetryCount++;
            
            if ($currentRetryCount >= $maxRetryCount) {
                // 超过最大重试次数，标记为发布失败
                addlog('releaseTask', "任务 {$torrentRelease->id} 的下载器 {$taskData->downloader_id} 连接失败，已达到最大重试次数{$maxRetryCount}，停止重试");
                $torrentRelease->task_status = 3; // 发布失败
                $torrentRelease->status = 99;
                $torrentRelease->retry_count = $currentRetryCount;
                $torrentRelease->save();
                return 99;
            } else {
                // 未达到最大重试次数，重置状态为待发布，继续重试
                addlog('releaseTask', "任务 {$torrentRelease->id} 的下载器 {$taskData->downloader_id} 暂时无法连接，将在下次重试 (第{$currentRetryCount}/{$maxRetryCount}次)");
                $torrentRelease->task_status = 0; // 重置为待发布状态
                $torrentRelease->status = 1; // 重置为待处理状态
                $torrentRelease->retry_count = $currentRetryCount;
                $torrentRelease->save();
                return false; // 返回false表示需要重试
            }
        }

        /*反差一下数据并整合成新的数据*/
        $siteData = SiteWorkService::getSiteData($torrentRelease->site_id);
        $torrentListData = TorrentListService::getTorrentListData($taskData->site_id, $taskData->torrent_id);
        addlog('releaseTask', "源站{$torrentListData->site_id},种子ID：{$torrentListData->torrent_id}");

        // 调试日志：检查源数据的tag和简介
        if (SystemService::getConfig(SystemService::ENABLE_RELEASE_DEBUG_LOG)) {
            addlog('releaseTask-Debug-源数据', "任务ID：{$torrentRelease->id}，目标站点：{$siteData->site_name}({$siteData->site_key})");
            addlog('releaseTask-Debug-源数据', "原始torrents_tag(JSON)：" . ($torrentListData->torrents_tag ?? 'NULL'));
            addlog('releaseTask-Debug-源数据', "原始torrent_small_descr：" . ($torrentListData->torrent_small_descr ?? 'NULL'));
            $decodedTags = json_decode($torrentListData->torrents_tag, true);
            addlog('releaseTask-Debug-源数据', "解码后tags数组：" . json_encode($decodedTags, JSON_UNESCAPED_UNICODE));
        }

        if (!empty($taskData->torrents_view_img)) {
            $torrentListData->torrents_view = $torrentListData->torrents_view . $taskData->torrents_view_img;
        }
        $torrentData = array(
            'id' => $torrentRelease->id,
            'site_name' => $siteData->site_name,
            'site_key' => $siteData->site_key,
            'site_url' => $siteData->site_url,
            'site_passkey' => $siteData->site_passkey,
            //            'site_cookie' => $siteData->site_cookie,
            'torrent_hash' => $taskData->torrent_hash,
            'torrent_path' => $taskData->torrent_path,
            'down_path' => $taskData->down_path,
            'mediaInfo' => $taskData->mediaInfo,
            'torrent_site_id' => $torrentListData->site_id,
            'torrent_id' => $torrentListData->torrent_id,
            'torrent_title' => $torrentListData->torrent_title,
            'torrents_type' => $torrentListData->torrents_type,
            'torrents_audio_code' => $torrentListData->torrents_audio_code,
            'torrents_medium' => $torrentListData->torrents_medium,
            'torrents_code' => $torrentListData->torrents_code,
            'torrents_resolution' => $torrentListData->torrents_resolution,
            'torrents_production_team' => $torrentListData->torrents_production_team,
            'torrents_small_descr' => $torrentListData->torrent_small_descr,
            'torrents_size' => $torrentListData->torrents_size,
            'torrents_view' => $torrentListData->torrents_view,
            'torrents_tag' => json_decode($torrentListData->torrents_tag, true),
            'torrents_hash' => $torrentListData->torrents_hash,
        );
        
        // 调试日志：检查构建后的torrentData
        if (SystemService::getConfig(SystemService::ENABLE_RELEASE_DEBUG_LOG)) {
            addlog('releaseTask-Debug-传递数据', "torrentData中的torrents_tag：" . json_encode($torrentData['torrents_tag'], JSON_UNESCAPED_UNICODE));
            addlog('releaseTask-Debug-传递数据', "torrentData中的torrents_small_descr：" . ($torrentData['torrents_small_descr'] ?? 'NULL'));
        }
        /*先check一下详情的最下面是不是包含三张图-如果没有图片的补充一张三张图*/

        addlog('releaseTask', "任务ID：{$torrentRelease->id}，初始化参数完成，开始网络请求");
        $apiData = ApiWorkService::torrentReleaseDetails($torrentListData->site_id, $torrentListData->torrent_id, $torrentRelease->site_id, $torrentData);
        addlog('releaseTask', "任务ID：{$torrentRelease->id}，网络请求完成");
        
        // 调试日志：检查API返回的数据
        if (SystemService::getConfig(SystemService::ENABLE_RELEASE_DEBUG_LOG)) {
            if ($apiData) {
                addlog('releaseTask-Debug-API返回', "任务ID：{$torrentRelease->id}，API返回数据状态：成功");
                addlog('releaseTask-Debug-API返回', "返回的torrents_tag：" . json_encode($apiData['torrents_tag'] ?? 'NULL', JSON_UNESCAPED_UNICODE));
                addlog('releaseTask-Debug-API返回', "返回的small_descr：" . ($apiData['small_descr'] ?? 'NULL'));
                addlog('releaseTask-Debug-API返回', "返回的descr长度：" . (isset($apiData['descr']) ? strlen($apiData['descr']) : 0) . "字符");
                addlog('releaseTask-Debug-API返回', "返回的name：" . ($apiData['name'] ?? 'NULL'));
            } else {
                addlog('releaseTask-Debug-API返回', "任务ID：{$torrentRelease->id}，API返回数据：NULL或FALSE", 'error');
            }
        }
        
        $torrentData['site_cookie'] = $siteData->site_cookie;
        //        return $apiData;
        return ReleaseService::releaseTorrentTask($torrentData, $apiData);
    }


    public static function pushReleaseTorrent($torrentRelease, $options = array())
    {
        addlog('pushReleaseTorrent', '开始操作发布');
        $torrent_path = false;
        try {
            $result = ReleaseService::getTorrentUrl($torrentRelease);
        } catch (\Throwable $e) {
            /*更新一下这个种子的时间*/
            $torrentRelease->updated_at = date('Y-m-d H:i:s');
            $torrentRelease->save();
            return false;
        }
        switch ($result['http_code']) {
            case 404:
                $torrentRelease->status = 99;
                $torrentRelease->save();
                return false;
                break;
        }
        $torrent_path = $result['path'];
        addlog('pushReleaseTorrent', "发布URL :{$torrent_path}");
        if (!$torrent_path) return false;
        
        // 检查下载器是否存在
        $downloaderExists = DownloaderModel::where('id', $torrentRelease->downloader_id)->exists();
        
        if (!$downloaderExists) {
            // 下载器已被删除，直接标记任务失败
            addlog('pushReleaseTorrent', "任务 {$torrentRelease->id} 的下载器 {$torrentRelease->downloader_id} 已被删除，标记任务失败");
            $torrentRelease->status = 99;
            $torrentRelease->save();
            return false;
        }
        
        /*推送种子*/
        $qb = QBittorrentService::createService($torrentRelease->downloader_id);
        addlog('pushReleaseTorrent', "尝试连接QB");
        if ($qb) {
            addlog('pushReleaseTorrent', "已连接到QB");
            $torrentTask = TorrentTaskModel::where('id', $torrentRelease->task_id)->first();
            if (empty($torrentTask)) return false;
            $torrentRelease->torrents_path = $torrent_path;
            $torrentRelease->torrents_hash = calculateTorrentHashWithBencode($torrent_path);
            $torrentRelease->status = 2;

            $tag = [];
            $tag[] = "[-CSAUTO]";
            $tag[] = "[-" . SiteWorkService::siteName($torrentRelease->site_id) . "]";
            $tag[] = "[{$torrentTask->torrent_hash}]";
            $downloaderData = DownloaderModel::where('id', $torrentRelease->downloader_id)->first();
            $up_speed = 0;
            if ($downloaderData) {
                if ($downloaderData->up_speed > 0) $up_speed = $downloaderData->up_speed;
            }
            $siteUpSpeed = (int)SiteWorkService::siteUpSpeed($torrentRelease->site_id);
            if ($siteUpSpeed > 0) {
                addlog('pushReleaseTorrent', "存在站点限速 {$siteUpSpeed}MB/S");
                $up_speed = $siteUpSpeed;
            }
            if ($up_speed > 0) $options['upLimit'] = intval(intval($up_speed) * 1024 * 1024);
            $options['skip_checking'] = 'true';
            if (!$qb->addTorrentByFile($torrent_path, self::$defaultFilePath, self::$releaseSiteCategory, $tag, $options)) {
                addlog('pushReleaseTorrent', "任务上传失败");
                return false;
            }
            if (SystemService::getConfig(SystemService::TASK_SKIP_CHECKING)) {
                $qb->setSuperSeeding($torrentTask->torrent_hash, (string)SystemService::getConfig(SystemService::TASK_SKIP_CHECKING));
            }
            $torrentRelease->save();
            //            addlog('pushReleaseTorrent', "任务更新完成");
            addlog('pushReleaseTorrent', "任务更新与发布完成");
            return true;
        } else {
            // 下载器存在但无法连接，更新时间戳等待重试
            // pushReleaseTorrent 不使用重试计数，因为它是后台持续重试的任务
            addlog('pushReleaseTorrent', "任务 {$torrentRelease->id} 的下载器 {$torrentRelease->downloader_id} 暂时无法连接，等待下次重试");
            $torrentRelease->updated_at = date('Y-m-d H:i:s');
            $torrentRelease->save();
            return false;
        }
    }


    public static function updateDownloaderStatus($downloaderItem, $siteList)
    {
        $l = [];
        $qb = QBittorrentService::createService($downloaderItem->id);
        if ($qb) {
            $checkComplete = static::$releaseCompleteNum;
            if ($downloaderItem->site_check_complete > 0) $checkComplete = $downloaderItem->site_check_complete;
            $torrentsList = $qb->getTorrents();
            $torrentsRelease = array();
            if (count($torrentsList) > 0) {
                foreach (TorrentReleaseModel::where('task_status', 1)->where('status', 1)->get() as $item) {
                    $torrentsRelease[$item->torrents_hash] = $item->site_id;
                }
            }
            foreach ($torrentsList as $item) {
                $torrentCheckComplete = $checkComplete;
                if (isset($torrentsRelease[$item['hash']])) {
                    $torrentSiteId = $torrentsRelease[$item['hash']];
                    if (isset($siteList[$torrentSiteId])) {
                        if ($siteList[$siteList]['site_check_complete'] > 0) $torrentCheckComplete = $siteList[$siteList]['site_check_complete'];
                    }
                }
                if ($item['category'] == static::$releaseSiteCategory && $item['num_complete'] >= $torrentCheckComplete) {
                    /*解析一下标签的信息*/
                    $torrentData = TorrentReleaseModel::where('torrents_hash', $item['hash'])->where('status', 2)->first();
                    if ($torrentData) {
                        $torrentData->status = 99;
                        $torrentData->save();
                        $qb->pauseTorrent($item['hash']);
                        $l[] = $item['hash'];
                    }
                }
            }
        }
        return $l;
    }
}
